requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        jquery: 'jquery.min',
        jquery_route: 'jquery.route',
        bootstrap: "../../bootstrap-3.3.5/dist/js/bootstrap.min",
        menu : "../modules/index/menu",
        config: "../common/config",
        common:'../common/common',
        arttemplateUtil: '../js/common/arttemplate-util',
        layer: '../plugins/layer/layer',
        validform:"../plugins/Validform/Validform_v5.3.2",
        	"webuploader" : "../plugins/webuploader/js/webuploader",
			"customUploader_bath" : "../plugins/webuploader/js/customUploader_bath",
			"kindeditor" : "../plugins/editor/kindeditor",
			"kindeditor_lang" : "../plugins/editor/lang/zh_CN",
			uploadify : '../plugins/uploadify/jquery.uploadify',
			filer: '../plugins/fileinput/js/new/jquery.filer'
    },
    waitSeconds : 15,
	map : {
		'*' : {
			'css' : 'css'
		}
	},
	shim : { // 引入没有使用requirejs模块写法的类库。backbone依赖underscore
		'jquery' : {
			exports : '$'
		},
		'bootstrap' : [ 'jquery','jquery_route'],
		'uploadify' : [ 'jquery',
				'css!../plugins/uploadify/uploadify.css' ],
		'customUploader_bath' : [
				'css!../plugins/webuploader/css/webuploader.css',
				'webuploader' ],
		'kindeditor_lang' : [
				'css!../plugins/editor/plugins/code/prettify.css',
				'kindeditor' ],
		'validform':['jquery'],
		'filer':['jquery']
	}
});


requirejs([ 'jquery', 'jquery_route', 'arttemplateUtil' ,'common','config','stringUtil', 'filer',
            'validform', 'customUploader_bath','kindeditor_lang','uploadify' ], 
            function($,jquery_route, arttemplateUtil,common,config,stringUtil,filer) {
	
	//绑定图片上传事件
    var uploadInit = function(uploadId) {
    	$(uploadId).filer({
            changeInput: '<div class="jFiler-input-dragDrop mb10"><a class="jFiler-input-choose-btn blue-light btn btn-primary">选择图片</a></div>',
            limit: 1,
            maxSize: 2,
            extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
            showThumbs: true,
            theme: "dragdropbox",
            templates: {
                box: '<ul class="jFiler-items-list jFiler-items-grid"></ul>',
                item: '<li class="jFiler-item" style="width: 100%">\
                            <div class="jFiler-item-container">\
                                <div class="jFiler-item-inner">\
                                    <div class="jFiler-item-thumb">\
                                        <div class="jFiler-item-status"></div>\
                                        <div class="jFiler-item-info">\
                                            <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\
                                            <span class="jFiler-item-others">{{fi-size2}}</span>\
                                        </div>\
                                        {{fi-image}}\
                                    </div>\
                                    <div class="jFiler-item-assets jFiler-row">\
                                        <ul class="list-inline pull-left">\
                                            <li>{{fi-progressBar}}</li>\
                                        </ul>\
                                        <ul class="list-inline pull-right">\
                                            <li><a class="icon-jfi-trash jFiler-item-trash-action"></a></li>\
                                        </ul>\
                                    </div>\
                                </div>\
                            </div>\
                        </li>',
                itemAppend: '<li class="jFiler-item" style="width: 49%">\
                                <div class="jFiler-item-container">\
                                    <div class="jFiler-item-inner">\
                                        <div class="jFiler-item-thumb">\
                                            <div class="jFiler-item-status"></div>\
                                            <div class="jFiler-item-info">\
                                                <span class="jFiler-item-title"><b title="{{fi-name}}">{{fi-name | limitTo: 25}}</b></span>\
                                                <span class="jFiler-item-others">{{fi-size2}}</span>\
                                            </div>\
                                            {{fi-image}}\
                                        </div>\
                                        <div class="jFiler-item-assets jFiler-row">\
                                            <ul class="list-inline pull-left">\
                                                <li><span class="jFiler-item-others">{{fi-icon}}</span></li>\
                                            </ul>\
                                            <ul class="list-inline pull-right">\
                                                <li><a class="icon-jfi-trash jFiler-item-trash-action"></a></li>\
                                            </ul>\
                                        </div>\
                                    </div>\
                                </div>\
                            </li>',
                progressBar: '<div class="bar"></div>',
                itemAppendToEnd: false,
                removeConfirmation: false,//删除是否提示
                _selectors: {
                    list: '.jFiler-items-list',
                    item: '.jFiler-item',
                    progressBar: '.bar',
                    remove: '.jFiler-item-trash-action'
                }
            },
            uploadFile: {
                url: config.apiRoot() + "/api/v1/storeUpload",
                data: config.setFullParameterArr({}),
                type: 'POST',
                enctype: 'multipart/form-data',
                beforeSend: function(){
                	var length = $(uploadId).parent().find(".jFiler-row").find(".jFiler-items-grid").find(".jFiler-item").length;
                	if(length > 1) {
                		$(uploadId).parent().find(".jFiler-row").find(".jFiler-items-grid").find(".jFiler-item:last").remove();
                	}
                	//上传的时候把编辑的图片预览窗隐藏
                	$(uploadId).parent().parent().find(".shanchu").parent().parent().hide();
                },
                success: function(data, el){
                	var jsondata = $.parseJSON(data); 
                	if(jsondata.code == "200") {
                		var parent = el.find(".jFiler-jProgressBar").parent();
                        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                            $("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
                        });
                        $(uploadId).parent().parent().find(".accurl").val(jsondata.data.path+jsondata.data.ext);
                	} else {
                		var parent = el.find(".jFiler-jProgressBar").parent();
                        el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                            $("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");    
                        });
                        //上传失败的时候把编辑的图片预览窗显示
                    	//$(uploadId).parent().parent().find(".shanchu").parent().parent().show();
                	}
                    
                    //console.log(jsondata);
                },
                error: function(el){
                    var parent = el.find(".jFiler-jProgressBar").parent();
                    el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
                        $("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");    
                    });
                    //上传失败的时候把编辑的图片预览窗显示
                	//$(uploadId).parent().parent().find(".shanchu").parent().parent().show();
                },
                statusCode: null,
                onProgress: null,
                onComplete: null
         },
		captions: {
			button: "Choose Files",
			feedback: "Choose files To Upload",
			feedback2: "files were chosen",
			drop: "Drop file here to Upload",
			removeConfirmation: "Are you sure you want to remove this file?",
			errors: {
				filesLimit: "只能选择 {{fi-limit}} 图片上传.",
				filesType: "只能上传图片.",
				filesSize: "{{fi-name}} 太大! 上传文件不超过{{fi-maxSize}} MB.",
				filesSizeAll: "选择的文件太大! 上传文件不超过 {{fi-maxSize}} MB."
			}
		}
      });
   };
   
   var initBtn = function(){
	   $("#ret_btn").click(function(){
			window.location.href="#sidedishes/noticelist";
		});
		
		
		$("#submit_btn").click(function(){
			//表单验证
			var name = $("#name");
			if(name.val() == ''){
				layer.alert("模板名称不能为空");
				return;
			}
			var title_img_url = $("#title_img_url");
			if(title_img_url.val() == ''){
				layer.alert("标题图片不能为空");
				return;
			}
			var title = $("#title");
			if(title.val() == ''){
				layer.alert("文章标题不能为空");
				return;
			}
			//设置按钮禁用，防止重复提交
			jQuery(this).attr('disabled','disabled');
			
	    	var obj = {};
	    	var id = $("#id").val()+"";
			if(id != ''){
				obj.id = id;
			}
	    	obj.name = name.val();
	    	obj.title_img_url = title_img_url.val();
	    	obj.title = title.val();
	    	obj.content_detail = app.kindeditor().html();
	    	
	    	console.info(obj);
	    	//提交
	    	common.common_ajax_request('/api/v1/deliver_prevue_content_save', obj, false,function(data,code,msg){
				if(code==200 && msg.businessCode==0){
	        		window.layer.alert('保存成功!', {
	      			  icon: 1,closeBtn:false
	      			}, function(){
	      				window.location.href="#sidedishes/noticelist";
	      			}); 
				}else{
					layer.alert(msg.businessNote);
				}
			}, "", "post"); 
	    	return;
		});
   };
    
    ////
	var app = {
			init : function(){
				app.kindeditor(true);
				uploadInit('#fileinput1');
				initBtn();
				
				var id = $("#id").val()+"";
				
				if(id != ''){
					$("#btitle").html("编辑配菜预告模板");
					var param = {id:id};
					common.common_ajax_request('/api/v1/queryDeliverPrevueContentById',param,false,function(data,code,msg){
						$("#name").val(data.name);
						$("#title").val(data.title);
						$("#title_img_url").val(data.title_img_url);
						$("#title_img").attr("src", config.imgRoot()+data.title_img_url);
						//设置详情
						$('#content_detail').html(data.content_detail);
						app.kindeditor().html(data.content_detail);
					});
				}
				
			},
			kindeditor : function(flag) {
				if(typeof app._kindeditorobj === 'undefined' || flag){
					// options为编辑配置属性
					var options = {
						filterMode : true,
						uploadJson : config.apiRoot() + '/api/seller/fexUpload.htm?'+$.param(config.setFullParameterArr({}),true),
						webpath : config.apiRoot(),
						imgpath : config.imgRoot(),
						width : '860px',
						height : '400px',
						resizeType : 1,
						allowImageUpload : true,
						allowFlashUpload : false,
						allowMediaUpload : false,
						allowFileManager : false,
						syncType : "form",
						afterCreate : function() {
							var self = this;
							self.sync();
						},
						afterChange : function() {
							var self = this;
							self.sync();
						},
						afterBlur : function() {
							var self = this;
							self.sync();
						},
						items : [ 'source', '|', 'fullscreen', 'undo', 'redo',
								'cut', 'copy', 'paste', 'plainpaste',
								'wordpaste', '|', 'justifyleft',
								'justifycenter', 'justifyright', 'justifyfull',
								'insertorderedlist', 'insertunorderedlist',
								'indent', 'outdent', 'subscript',
								'superscript', '|', 'selectall', 'clearhtml',
								'quickformat', '|', 'formatblock', 'fontname',
								'fontsize', '|', 'forecolor', 'hilitecolor',
								'bold', 'italic', 'underline', 'strikethrough',
								'lineheight', 'removeformat', '|',
								'webuploader_bath', 'table', 'hr', 'emoticons',
								'link', 'unlink' ]
					};
					app._kindeditorobj=KindEditor.create('#content_detail', options);
				}
				return app._kindeditorobj;
			}
	};
	app.init();
});